<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/29 0029
 * Time: 下午 5:47
 */
namespace Api\Controller;

class PayController extends ApiController{

    public function __construct(){
        parent::__construct();
        if(!$this->user_info){
            $this->error($this->error,999);
            exit;
        }
    }

    //获取开放的支付方式
    public function pay(){

        //获取开通的支付方式
        $type = I('type');

        $where = ['status' => 1, 'client_app' => 1];
//        if($type == 'recharge'){
//            $where['class_name'] = ['not in',['Balance','Offline']];
//        }
        $paymentMethods = M('Payment')->where($where)->order('sort ASC')->field('id AS sid,name,config_param,logo,class_name')->select();
        $return = [];
        foreach ($paymentMethods as $key => $val) {
            $config = json_decode($val['config_param'], true);
            // $paymentMethods[$key]['channel'] = $config['channel'];
            $paymentMethods[$key]['desc'] = $config['desc'];
            unset($paymentMethods[$key]['config_param']);
            if (!$config['channel']) {
                continue;
            }
            $return[$config['channel']] = $paymentMethods[$key];

        }
        $return = [
            'setting'=>$this->setting,
            'pays'  =>  $return,
        ];
        $this->success($return);


//        $return = [
//            'setting'=>$this->setting,
//            'pays'  =>  $pays,
//        ];

//        $this->success($return,'');
    }

    //生成订单
    public function create_order(){
        $cash = I('cash',0,'intval');
        $method = I('method',0,'intval');
        if($cash < 1){
            $this->error('订单金额有误');
        }

        if($method < 1){
            $this->error('支付方式有误');
        }

        $payment = M('Payment')->find($method);
        if(empty($payment)){
            $this->error('没有找到该支付方式');
        }
        $config = json_decode($payment['config_param'],true);

        $backParam = I('_back', '') ? array('_back' => I('_back', '')) : array();
        $data = array(
            'order_id'  =>  $this->createOrderId(),
            'user_id'   =>  $this->user_info['id'],
            'amount'    =>  $cash,
            'add_time'  =>  time(),
            'method'    =>  $method,
            'remark'    =>  "App客户端充值",
            'type'      =>  '普通',
        );

        if (M('Order')->data($data)->add()) {
            $this->success(['payUrl' => U('/payment/dopay', array_merge(['order_id' => $data['order_id'], 'method' => $method], $backParam), false, true),'channel'=>$config['channel']]);
        } else {
            $this->error('订单创建失败');
        }

    }

    protected function createOrderId() {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}